package com.jeasonzhao.commons.logger;

public abstract class MessageBasedLogListener implements LogListener
{
    private static final java.text.SimpleDateFormat DATE_Format = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    public MessageBasedLogListener()
    {
        super();
    }

    public static final String formatMessage(LogLevel logLevel,String strPrefix2,String strMessage,Throwable excep)
    {
        return formatMessage(logLevel.toString(),strPrefix2,strMessage,excep);
    }

    protected static String getCallerName()
    {
        Throwable e = new Throwable();
        for(StackTraceElement ste : e.getStackTrace())
        {
            if(ste.getClassName().startsWith(MessageBasedLogListener.class.getPackage().getName()) == false)
            {
                String str = ste.getClassName();
                int nx = str.lastIndexOf('.');
                if(nx > 0)
                {
                    str = str.substring(nx + 1);
                }
                return "[" + str + ":" + ste.getLineNumber() + "]";
            }
        }
        return null;
    }

    public static final String formatMessage(String level,String strPrefix2,String strMessage,Throwable excep)
    {
        if(null == strMessage && null == excep)
        {
            return null;
        }
        StringBuffer buf = new StringBuffer();
        buf.append(DATE_Format.format(new java.util.Date()));
        buf.append("[" + level + "] ");
        String cn = getCallerName();
        if(null != cn)
        {
            buf.append(cn + " ");
        }
        if(null != strPrefix2)
        {
            buf.append(strPrefix2 + ">>");
        }
        if(null == strMessage && null != excep)
        {
            buf.append(excep.getMessage());
        }
//        else if(null != strMessage && null == excep)
//        {
//            buf.append(strMessage);
//        }
        else
        {
            buf.append(strMessage);
        }
//        String x = buf.toString();
        Throwable t = excep;
        int Level = 0;
        while(null != t)
        {
            StringBuffer strPrefix = new StringBuffer();
            for(int n = 0;n < Level;n++)
            {
                strPrefix.append("\t");
            }
            buf.append("\n" + strPrefix + t.getMessage());
            for(StackTraceElement tr : t.getStackTrace())
            {
                buf.append("\n" + strPrefix.toString() + tr.toString());
            }
            t = t.getCause();
            Level++;
        }
        return buf.toString();
    }

}
